const util = require('util');
const debug = util.debuglog('oil-game:welfare:action');

const BigNumber = require("bignumber.js");
const {
  WELFARE_PRIZE,    //奖品列表
  MoneyType,
  OIL_PUMP_RESULT,    //首页油泵奖品
} = require("./consts");
const {
  formatCoins
} = require("../../upgrade/lib/action");

//生成奖品列表
exports.createPrizeList = function(total_oil) {
  //奖品
  let list = [];
  for (let i = 0; i < WELFARE_PRIZE.length; i++) {
    let prize = {};
    //当单日石油小于15时可以产生石油
    if (total_oil < 15) {
      prize.type = MoneyType.OIL;//奖品类型
      let arr = [1, 2, 3];
      let index = Math.floor((Math.random() * arr.length));
      prize.value = arr[index];
      if (prize.value < 1) {
        prize.value = 1;
      }
      prize.showVal = prize.value;
    } else {
      let {value, showVal} = randomGold();
      prize.type = MoneyType.GOLD;
      prize.value = value;
      prize.showVal = showVal;
    }
    prize.id = i;
    list.push(prize);
  }
  return list;
}

//生成油泵奖励结果
exports.createOilPumpResult = function()  {
  //获取奖品结果
  let min = 0, max = 100;
  let randomPrize = parseInt(Math.random()*(max-min+1)+min,10);
  debug("首页油泵抽奖结果参数 %s", randomPrize);
  //获取奖品结果
  let prizeResult = {};
  //上一次奖品的最大值
  let prevEnd = 0;
  for(let i = 0; i < OIL_PUMP_RESULT.length; i++){
    let range = (max - min) * Number(OIL_PUMP_RESULT[i].probability);
    let rangeMax = prevEnd + range;
    debug("首页抽奖结果范围 %s  -  %s", prevEnd, rangeMax)
    if(randomPrize >= prevEnd && randomPrize <= rangeMax){
      prizeResult = OIL_PUMP_RESULT[i];
      break;
    }
    prevEnd = rangeMax;
  }
  debug("首页油泵获取抽奖结果 %s", prizeResult)
  return prizeResult;
}

//生成油泵的随机金币
exports.createOilPumpCoins = function(prizeResult){
  let min = prizeResult.min;
  let max = prizeResult.max;
  let coins = parseInt(Math.random()*(max-min+1)+min,10);
  let showCoins = formatCoins(new BigNumber(coins));
  debug("生成油泵随机金币 min = %s max = %s coins = %s showCoins = %s", min, max, coins, showCoins);
  return {coins, showCoins};
}

//生成随机金币数量，随机500-10M
function randomGold() {
  let minNum = 500;   //金币最少为500
  let maxNum = 10000000;    //金币最大为10M
  let value = parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10)
  //格式化后的金币
  let showVal = formatCoins(new BigNumber(value));
  return {value, showVal};
}
